import React, { useEffect, useState, useMemo, useRef, useReducer, useCallback } from "react";
import {
    pqsstartWkInfo_query_page,
    getPdfInfo,
    forceBack,
    backout,
    delData,
    downloadPdf,
} from "src/api/pqsstartWkInfo";
import {
    NavBar,
    Tabs,
    List,
    SearchBar,
    Skeleton,
    Empty,
    Dialog,
    FloatingBubble,
} from "antd-mobile";
import { AddOutline } from "antd-mobile-icons";
import { SearchOutline } from "antd-mobile-icons";
import BetterScroll from "pages/components/betterScroll";
import Btns from "pages/components/btns";
import { API_URL, PDF_URL, FILE_VIEW, FILE_VIEW_ONLINE } from "src/config";
import { tableField } from "./config";
import { PreviewPdf, isNormalBrowser, clearRefreshPage, guid, findTree } from "src/utils/index";
import { getBusinessData } from "src/utils/basic-business";
import { debounce } from "lodash";
import { useActivate, useUnactivate, withActivation } from "react-activation";
import axios from "src/api/index";
import Cookies from "js-cookie";
import "./index.scss";
import "./detail.scss";
import { locationShape, historyShape, storeShape } from "src/propType";
import Toast from "src/pages/components/clickableToast";
import WorkflowCommit from "./commit/workflow-commit";

let key = guid();

function listReducer(state, action) {
    switch (action.type) {
        case "add_list": {
            return {
                ...state,
                dataSource: action.dataSource,
                loading: action.loading,
                total: action.total,
                page: action.page,
            };
        }
        case "before_add": {
            return {
                ...state,
                loading: true,
            };
        }
    }
}

const initialList = { dataSource: [], loading: true, page: 1, limit: 50, total: 0 };

function CommonListView(props) {
    const [list, setList] = useReducer(listReducer, initialList);
    const lastList = useStateRef(list);

    const workflowRef = useRef(null);
    const [selectTable, setSelectTable] = useState();

    const [activityKey, setActivityKey] = useState("0");
    const [searchVisible, setSearchVisible] = useState(false);

    const { store, location, history } = props;
    const user = store.user.userData;

    const singleDataItem = useMemo(() => {
        return store.user.basicBusinessDataList.find(opItem => {
            if (location.pathname === opItem.modelPath) {
                return opItem;
            }
        });
    }, [location.pathname]);

    const getList = (cb, restPage, reportNo) => {
        let { page, dataSource } = lastList.current;
        const isRestPage = restPage || searchVisible;
        page = isRestPage ? 1 : page;
        setList({
            type: "before_add",
        });
        pqsstartWkInfo_query_page({
            page,
            limit: 50,
            moduleId: singleDataItem.tableId,
            moduleName: singleDataItem.modelName,
            reportNo: isRestPage ? reportNo : undefined,
        }).then(res => {
            const { code, data, total } = res;
            if (code === 200) {
                setList({
                    type: "add_list",
                    dataSource: isRestPage ? data : [...dataSource, ...data],
                    loading: false,
                    total,
                    page: ++page,
                });
            } else {
                Toast.show({
                    icon: "fail",
                    content: res.msg,
                });
            }
            cb && cb();
        });
    };

    const refreshList = () => {
        getList(null, true);
    };

    const toViewPdf = async record => {
        const isView = await Dialog.confirm({ content: "是否预览pdf" });
        if (!isView) return;

        Toast.show({
            icon: "loading",
            content: "",
            duration: FILE_VIEW_ONLINE ? 2000 : 0,
        });
        const res = await getPdfInfo(record.kid);
        const { code, data, msg } = res;
        const hasFile = data && Array.isArray(data) ? data.length : data;
        if (code === 200 && hasFile) {
            const fileUrl = data && (data.pdfName || data.pdfPath || data.svrFullPath);
            const url = (PDF_URL + fileUrl).replace(/\\/g, "/");

            // if (!isNormalBrowser()) {
            //     const url = `${API_URL}/wpfile/downloadPdf?dbName=GPMSPQS&recordId=${record.kid}&title=${record.moduleName}.pdf`;
            //     PreviewPdf(url);
            //     return;
            // }

            if (FILE_VIEW_ONLINE) {
                // 在线预览方式
                // let viewUrl = `${url}&fullfilename=${record.kid}.pdf&isApp=1`;
                // PreviewPdf(viewUrl);
                PreviewPdf(fileUrl);
            } else {
                //downLoadFile
                axios({
                    method: "GET",
                    customError: true,
                    _ingore: true,
                    url: FILE_VIEW,
                    params: {
                        fileName: `${record.kid}.pdf`,
                        cookies: `CRBIMSSOJWT=${Cookies.get("CRBIMSSOJWT")}`,
                        url,
                        isApp: 1,
                    },
                }).then(res => {
                    if (res.msg === "SUCCESS") {
                        Toast.show({
                            icon: "success",
                            content: "",
                        });
                        res.data && window.open(res.data);
                    } else {
                        Toast.show({
                            icon: "fail",
                            content: res.msg,
                        });
                    }
                });
            }
        } else {
            Toast.show({
                icon: "fail",
                content: hasFile ? msg : "PDF文件不存在",
                afterClose: () => {},
            });
            return;
        }
    };

    const forceBackFn = async table => {
        const isBack = await Dialog.confirm({ content: "确定要退回吗?" });
        if (!isBack) return;
        const res = await forceBack({
            kid: table.kid,
            ...table,
            stateId: -2,
            stateName: "退回",
        });
        if (res.success) {
            Toast.show({
                icon: "success",
                content: "提交成功",
            });
            refreshList();
        }
    };

    const backoutFn = async table => {
        const isBack = await Dialog.confirm({ content: "确定要撤回吗?" });
        if (!isBack) return;
        const res = await backout(table.kid);
        if (res.success) {
            Toast.show({
                icon: "success",
                content: "撤回成功",
            });
            refreshList();
        }
    };

    const delDataFn = async table => {
        const isBack = await Dialog.confirm({ content: "此操作将永久删除数据, 是否继续?" });
        if (!isBack) return;
        const res = await delData(table.kid);
        if (res.success) {
            refreshList();
        }
    };

    const commitCallBack = () => {
        refreshList();
    };

    useEffect(() => {
        getList();
    }, []);

    useActivate(() => {
        key = guid();
        clearRefreshPage(() => getList(null, true));
    });

    const changeTab = activityKey => {
        setActivityKey(activityKey);
    };

    //上拉加载
    const pullingUp = useCallback(() => {
        let { page, limit, total } = lastList.current;
        if (page > Math.ceil(total / limit)) {
            Toast.show({
                content: "没有更多数据了!",
            });
            return;
        }
        getList();
    }, [activityKey, list.dataSource]);

    const currenTabList = useMemo(() => {
        return list.dataSource.filter(table => {
            switch (activityKey) {
                case "1":
                    return table.stateId < 0;
                case "2":
                    return table.stateId > 0;
                case "3":
                    return table.stateId === 0;
                default:
                    return table;
            }
        });
    }, [activityKey, list.dataSource]);

    const hasData = currenTabList?.length;

    const right = (
        <div
            style={{ fontSize: 24 }}
            onClick={() => {
                setSearchVisible(true);
            }}
        >
            <SearchOutline />
        </div>
    );

    const title = encodeURIComponent(singleDataItem?.label) || "";

    const btns = [
        {
            label: "删除",
            key: "1",
            fn: table => delDataFn(table),
            hidden: table => {
                const hasNoSignStep = table.stateId === undefined || table.stateId === null;
                return !(user.userId === table.addUserId && (hasNoSignStep || table.stateId < 0));
            },
        },
        {
            label: "编辑",
            key: "2",
            fn: table => {
                table.kid &&
                    history.push(
                        `${location.pathname}/detail?page=edit&kid=${table.kid}&title=${title}&key=${key}`,
                    );
            },
            hidden: table => {
                return !(
                    (user.userId === table.addUserId &&
                        (table.stateId === undefined ||
                            table.stateId === null ||
                            table.stateId < 0)) ||
                    table.addUserId === null ||
                    table.addUserId === 0
                );
            },
        },
        {
            label: "提交",
            key: "3",
            fn: table => {
                setSelectTable(table);
                workflowRef.current.visibleCb(true);
            },
            hidden: table => {
                //未开发表格 先暂时展示详情界面
                if (
                    !["/WorkStartStandard/bidsection", "/WorkStartStandard/UnitProject"].includes(
                        location.pathname,
                    )
                )
                    return true;
                return !(table.stateId < 0 && user.userId === table.addUserId);
            },
        },
        {
            label: "审核",
            key: "4",
            fn: table => {
                table.kid &&
                    history.push(
                        `${location.pathname}/detail?page=sign&kid=${table.kid}&title=${title}&key=${key}`,
                    );
            },
            hidden: table => {
                const isRepCommit = false;
                return isRepCommit
                    ? !(
                          table.stateId === 1 &&
                          table.issueUserId &&
                          user.userId === table.issueUserId
                      )
                    : !(table.chkStateId == "666");
            },
        },
        {
            label: "撤回",
            key: "5",
            fn: table => backoutFn(table),
            hidden: table => {
                if (table.stateId !== undefined) {
                    // 撤回（审核中是当前登录身份提交的记录）

                    const isNotice = true; //是督办通知模块
                    const isInstruction = false;

                    if (isNotice) {
                        return !(
                            (table.stateId == 1 ||
                                (table.stateId == 2 && table.noticeTypeId == 2)) &&
                            user.userId == table.addUserId
                        );
                    } else {
                        if (isInstruction) {
                            return !(
                                (table.stateId == 1 || table.stateId == 2) &&
                                user.userId == table.addUserId
                            );
                        } else {
                            // 撤回（审核中是当前登录身份提交的记录）
                            if (table.stateId == 1 && user.userId == table.addUserId) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            },
        },
        {
            label: "退回",
            key: "6",
            fn: table => forceBackFn(table),
            hidden: table => {
                const btns = store.user.basicBusinessDataList_2;
                if (btns && btns.length > 0) {
                    const hasNoSignStep = table.stateId === undefined || table.stateId === null; //是否存在  stateId 状态标识
                    const opt = btns[0];
                    if (opt && opt.label && opt.label.indexOf(user.userId) > -1) {
                        return !(hasNoSignStep || table.stateId === 0);
                    }
                }
                return true;
            },
        },
        {
            label: "查看",
            key: "7",
            fn: table => toViewPdf(table),
        },
    ];

    const getStateName = stateId => {
        switch (true) {
            case stateId === 0:
                return {
                    className: "green",
                    value: "已审核",
                };
            case stateId < 0:
                return {
                    className: "yellow",
                    value: "待提交",
                };
            case stateId > 0:
                return {
                    className: "orange",
                    value: "审核中",
                };
        }
    };

    const BusinessData = useMemo(() => {
        const baseUrl = getBusinessData(store, location, "baseUrl");
        const useTypeOfWorkflow = getBusinessData(store, location, "tableId");
        const optionOne =
            getBusinessData(store, location, "optionOne", useTypeOfWorkflow) ||
            getBusinessData(store, location, "optionOne", useTypeOfWorkflow);
        const useWorkflow = getBusinessData(store, location, "useWorkflow");
        const workflowModule = getBusinessData(
            store,
            location,
            "workflowModule",
            selectTable?.projTypeId,
        );
        let workflowModuleCur = workflowModule;
        if (useWorkflow) {
            workflowModuleCur = workflowModule + "-" + (selectTable?.[useWorkflow] || 1);
        }

        return {
            baseUrl,
            optionOne,
            workflowModuleCur,
        };
    }, [selectTable]);

    return (
        <div className="common-list">
            {searchVisible ? (
                <div className="search adm-nav-bar">
                    <SearchBar
                        placeholder="请输入编号"
                        showCancelButton={() => true}
                        autoFocus
                        onCancel={() => {
                            setSearchVisible(false);
                            refreshList();
                        }}
                        onChange={debounce(
                            value => {
                                value && value.trim() !== "" && getList(null, null, value);
                            },
                            700,
                            { trailing: true },
                        )}
                    />
                </div>
            ) : (
                <NavBar back="返回" right={right} onBack={() => props.history.go(-1)}>
                    {singleDataItem.modelName}
                </NavBar>
            )}
            <Tabs
                activeKey={activityKey}
                onChange={changeTab}
                style={{
                    backgroundColor: "#fff",
                }}
            >
                <Tabs.Tab title="全部" key="0" />
                <Tabs.Tab title="待提交" key="1" />
                <Tabs.Tab title="审核中" key="2" />
                <Tabs.Tab title="已审核" key="3" />
            </Tabs>
            <div className="scroll-container">
                <BetterScroll pullingUp={pullingUp}>
                    <div className={`${hasData ? "common-list-container" : "empty"}`}>
                        {list.loading ? (
                            <Skeleton.Paragraph lineCount={10} animated />
                        ) : hasData ? (
                            currenTabList.map(table => {
                                const { kid, stateId } = table;
                                return (
                                    <div className="list-container" key={kid}>
                                        <List.Item
                                            arrowIcon={false}
                                            clickable={false}
                                            onClick={e => {
                                                kid &&
                                                    history.push(
                                                        `${location.pathname}/detail?page=view&kid=${kid}&title=${title}&key=${key}`,
                                                    );
                                            }}
                                        >
                                            <div className="content">
                                                {tableField[singleDataItem.tableId]?.map(
                                                    (field, i) => {
                                                        const label = field.label;
                                                        const value = table[field.name];
                                                        const isStateName =
                                                            field.name === "stateId";
                                                        return (
                                                            <p key={i}>
                                                                <span>{label}</span>
                                                                {isStateName ? (
                                                                    <span
                                                                        className={`${
                                                                            getStateName(value)
                                                                                .className
                                                                        }`}
                                                                        onClick={e => {
                                                                            e.stopPropagation();
                                                                            history.push(
                                                                                `/StatusFlow?kid=${table.kid}&stateId=${table.stateId}&addUserId=${table.addUserId}&pathname=${location.pathname}&key=${key}`,
                                                                            );
                                                                        }}
                                                                    >
                                                                        {field.isDate
                                                                            ? value?.substring(
                                                                                  0,
                                                                                  10,
                                                                              )
                                                                            : getStateName(value)
                                                                                  .value}
                                                                    </span>
                                                                ) : (
                                                                    <span>
                                                                        {field.isDate
                                                                            ? value?.substring(
                                                                                  0,
                                                                                  10,
                                                                              )
                                                                            : value}
                                                                    </span>
                                                                )}
                                                            </p>
                                                        );
                                                    },
                                                )}
                                                <p>
                                                    <span>附件：</span>
                                                    <span
                                                        className="blue"
                                                        onClick={e => {
                                                            e.stopPropagation();
                                                            kid &&
                                                                props.history.push(
                                                                    `/FileInfo?${kid}`,
                                                                );
                                                        }}
                                                    >
                                                        查看附件
                                                    </span>
                                                </p>
                                            </div>
                                            <Btns source={table} btns={btns} />
                                        </List.Item>
                                    </div>
                                );
                            })
                        ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                    </div>
                </BetterScroll>
            </div>
            <FloatingBubble
                style={{
                    "--initial-position-bottom": "70px",
                    "--initial-position-right": "24px",
                    "--edge-distance": "24px",
                }}
                onClick={() =>
                    history.push(`${location.pathname}/detail?page=add&title=${title}&key=${key}`)
                }
            >
                <AddOutline fontSize={32} />
            </FloatingBubble>
            <WorkflowCommit
                ref={workflowRef}
                baseUrl={BusinessData.baseUrl}
                optionOne={BusinessData.optionOne}
                workflowModule={BusinessData.workflowModuleCur}
                userData={user}
                page={""}
                kid={selectTable?.kid}
                commitCallBack={commitCallBack}
            />
        </div>
    );
}

export function useStateRef(state) {
    const stateRef = useRef();
    useEffect(() => {
        stateRef.current = state;
        return () => {};
    }, [state]);
    return stateRef;
}

CommonListView.propTypes = {
    store: storeShape,
    history: historyShape,
    location: locationShape,
};

export default CommonListView;
